<template>
    <div class="house-detail">
        <Header />
        
        <PageBanner
            title="房源详情"
            :breadcrumbs="[
                { title: '房产', path: '/house' },
                { title: '房源详情' }
            ]"
        />
        
        <!-- 主要内容区域 -->
        <div class="container">
            <div class="content-wrapper">
                <!-- 房源基本信息 -->
                <div class="basic-info">
                    <div class="left">
                        <el-carousel height="480px" :interval="4000" arrow="hover">
                            <el-carousel-item v-for="(image, index) in houseImages" :key="index">
                                <img :src="image" :alt="houseDetail.title" />
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                    <div class="right">
                        <h1 class="title">{{ houseDetail.title }}</h1>
                        <div class="price">
                            <span class="amount">¥{{ formatPrice(houseDetail.price) }}</span>
                        </div>
                        <div class="tags">
                            <el-tag v-for="tag in houseDetail.tags" :key="tag" size="small">{{ tag }}</el-tag>
                        </div>
                        <div class="info-items">
                            <div class="item">
                                <svg-icon name="house/info/area" />
                                <span>{{ houseDetail.area }}㎡</span>
                            </div>
                            <div class="item">
                                <svg-icon name="house/info/bedroom" />
                                <span>{{ houseDetail.bedroom }}室{{ houseDetail.livingRoom }}厅</span>
                            </div>
                            <div class="item">
                                <svg-icon name="house/info/floor" />
                                <span>{{ houseDetail.floor }}层/共{{ houseDetail.totalFloor }}层</span>
                            </div>
                            <div class="item">
                                <svg-icon name="house/info/face" />
                                <span>{{ houseDetail.orientation }}</span>
                            </div>
                        </div>
                        <div class="address">
                            <svg-icon name="house/info/location" />
                            <span>{{ houseDetail.address }}</span>
                        </div>
                        <div class="buttons">
                            <el-button 
                                size="large" 
                                type="primary" 
                                @click="contactAgent"
                            >
                                    <svg-icon name="house/info/phone" />
                                    联系经纪人
                            </el-button>
                            <el-button size="large" @click="toggleCollect">
                                <svg-icon :name="isCollected ? 'house/info/star-filled' : 'house/info/star'" />
                                {{ isCollected ? '取消收藏' : '收藏' }}
                            </el-button>
                        </div>
                    </div>
                </div>
                
                <!-- 房源特色 -->
                <div class="features card">
                    <h2 class="section-title">房源特色</h2>
                    <div class="feature-list">
                        <div v-for="(feature, index) in houseDetail.features" :key="index" class="feature-item">
                            <svg-icon :name="feature.icon" />
                            <div class="feature-content">
                                <h3>{{ feature.title }}</h3>
                                <p>{{ feature.description }}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 房源描述 -->
                <div class="description card">
                    <h2 class="section-title">房源描述</h2>
                    <div class="description-content" v-html="houseDetail.description"></div>
                </div>
                
                <!-- 配套设施 -->
                <div class="facilities card">
                    <h2 class="section-title">配套设施</h2>
                    <div class="facility-list">
                        <div v-for="facility in houseDetail.facilities" :key="facility.name" class="facility-item">
                            <svg-icon :name="facility.icon" :class="{ disabled: !facility.available }" />
                            <span :class="{ disabled: !facility.available }">{{ facility.name }}</span>
                        </div>
                    </div>
                </div>
                
                <!-- 地图 -->
                <div class="map-container card">
                    <h2 class="section-title">位置周边</h2>
                    <el-tabs v-model="activePoiType" tab-position="top" class="poi-tabs">
                        <el-tab-pane label="公交" name="公交"></el-tab-pane>
                        <el-tab-pane label="地铁" name="地铁"></el-tab-pane>
                        <el-tab-pane label="医院" name="医院"></el-tab-pane>
                        <el-tab-pane label="银行" name="银行"></el-tab-pane>
                        <el-tab-pane label="休闲娱乐" name="休闲娱乐"></el-tab-pane>
                        <el-tab-pane label="购物" name="购物"></el-tab-pane>
                        <el-tab-pane label="餐饮" name="餐饮"></el-tab-pane>
                        <el-tab-pane label="运动健身" name="运动健身"></el-tab-pane>
                    </el-tabs>
                    <div class="map-wrapper">
                        <div id="amap-container" class="map"></div>
                        <div class="poi-list">
                            <div v-if="poiData[activePoiType].length > 0">
                                <div class="poi-item" v-for="(poi, index) in poiData[activePoiType]" :key="index" @click="showFacilityLocation(poi)">
                                    <svg-icon :name="getIconName(activePoiType)" />
                                    <span>{{ poi.name }}（{{ poi.distance }}米）</span>
                                </div>
                            </div>
                            <div v-else class="no-data">暂无数据</div>
                        </div>
                        <!-- 添加地图控件 -->
                        <div class="map-controls">
                            <button class="control-btn" @click="getCurrentLocation" title="定位">
                                        <svg-icon name="map/location" />
                                    </button>
                                    <button class="control-btn" @click="zoomIn" title="放大">
                                        <svg-icon name="map/zoom-in" />
                                    </button>
                                    <button class="control-btn" @click="zoomOut" title="缩小">
                                        <svg-icon name="map/zoom-out" />
                                    </button>
                        </div>
                    </div>
                </div>
                
                <!-- 经纪人信息 -->
                <div class="agent-info card">
                    <h2 class="section-title">经纪人信息</h2>
                    <div class="agent-content" v-if="houseDetail.agentId">
                        <div class="agent-avatar">
                            <img :src="agentAvatar" :alt="houseDetail.agentName" />
                </div>
                        <div class="agent-details">
                            <h3>{{ houseDetail.agentName || '暂无经纪人' }}</h3>
                            <p class="agent-title">{{ houseDetail.agentTitle || '房产顾问' }}</p>
                            <div class="agent-stats">
                                <div class="stat-item">
                                    <span class="value">{{ houseDetail.agentStats?.experience || houseDetail.agentExperience || 0 }}年</span>
                                    <span class="label">从业经验</span>
                                </div>
                                <div class="stat-item">
                                    <span class="value">{{ houseDetail.agentStats?.deals || houseDetail.agentDeals || 0 }}+</span>
                                    <span class="label">成交量</span>
                                </div>
                                <div class="stat-item">
                                    <span class="value">{{ houseDetail.agentStats?.rating || houseDetail.agentRating || 0 }}分</span>
                                    <span class="label">用户评分</span>
                                </div>
                            </div>
                            <el-button 
                                type="primary" 
                                @click="contactAgent"
                            >
                                <el-icon><chat-dot-round /></el-icon> 
                                联系经纪人
                            </el-button>
                        </div>
                    </div>
                    <div class="no-agent" v-else>
                        <div class="empty-state">
                            <svg-icon name="common/no-data" />
                            <p>暂无经纪人信息</p>
                            <div class="empty-desc">该房源暂未指定经纪人，可联系客服了解更多信息</div>
                            <el-button 
                                type="primary" 
                                @click="contactCustomerService"
                            >
                                联系客服
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <Footer />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, shallowRef, onUnmounted, nextTick, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getHouseDetail, collectHouse } from '@/api/house'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'
import PageBanner from '@/views/common/PageBanner.vue'
import { ElMessage, ElButton, ElCarousel, ElCarouselItem, ElTag, ElTabs, ElTabPane } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { addFavorite, removeFavorite, checkFavorite } from '@/api/favorite'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { getFullImageUrl } from '@/utils/imageUrl'
import { enrichHouseWithAgentInfo } from '@/utils/agentHelper'
import { getAgentInfo, getAgentList, getAgentUserId, startChat } from '@/api/agent'

const map = shallowRef(null)
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const isCollected = ref(false)
const mapLoading = ref(true)
const mapContainer = ref(null)
const drivingRoute = ref(null)
const activePoiType = ref('公交')
const userStore = useUserStore()
const loginStore = useLoginStore()

// 房源详情数据
const houseDetail = reactive({
    houseId: '1',
    title: '北京市海淀区中关村 清华北大双学区房 精装修5室3厅',
    price: 25800,
    coverImage: '',  // 封面图片
    images: [  // 主图列表
        // 默认图片，如果API未返回数据将显示这些
        '/images/house/default1.jpg'
    ],
    tags: ['精装修', '拎包入住', '南北通透', '地铁沿线', '配套齐全'],
    area: 280,
    bedroom: 5,
    bathroom: 3,
    livingRoom: 2,
    floor: 12,
    totalFloor: 33,
    orientation: '南北',
    address: '北京市海淀区中关村大街',
    features: [
        {
            icon: 'house/features/location',
            title: '顶级学区房',
            description: '紧邻清华大学、北京大学，步行可达人大附中，教育资源丰富。'
        },
        {
            icon: 'house/features/decoration',
            title: '精装修房源',
            description: '全屋采用环保材料精装修，品牌家电齐全，拎包即可入住。'
        },
        {
            icon: 'house/features/layout',
            title: '户型方正',
            description: '南北通透，采光充足，空间布局合理，居住舒适度高。'
        },
        {
            icon: 'house/features/community',
            title: '高档小区',
            description: '小区环境优美，24小时安保，配套设施完善，居住安全舒适。'
        }
    ],
    description: `
        <p>本房源位于北京市海淀区中关村，是一套精装修的5室3厅双学区房。</p>
        <p>房源亮点：</p>
        <p>1. 位置优越：紧邻清华大学、北京大学，步行可达人大附中。</p>
        <p>2. 精装修：全屋采用环保材料精装修，品牌家电齐全。</p>
        <p>3. 户型方正：南北通透，采光充足，空间布局合理。</p>
        <p>4. 配套齐全：中关村科技园区配套设施一应俱全。</p>
        <p>5. 人文环境：周边高校云集，文化氛围浓厚。</p>
    `,
    facilities: [
        { name: '冰箱', icon: 'house/facilities/fridge', available: true },
        { name: '洗衣机', icon: 'house/facilities/washer', available: true },
        { name: '空调', icon: 'house/facilities/ac', available: true },
        { name: '热水器', icon: 'house/facilities/heater', available: true },
        { name: '电视', icon: 'house/facilities/tv', available: true },
        { name: '宽带', icon: 'house/facilities/wifi', available: true },
        { name: '衣柜', icon: 'house/facilities/wardrobe', available: true },
        { name: '天然气', icon: 'house/facilities/gas', available: true },
        { name: '暖气', icon: 'house/facilities/heating', available: true },
        { name: '床', icon: 'house/facilities/bed', available: true },
        { name: '沙发', icon: 'house/facilities/sofa', available: true },
        { name: '餐桌', icon: 'house/facilities/table', available: true }
    ],
    agentName: '张经理',
    agentAvatar: '/images/agent/avatar1.jpg',
    agentTitle: '资深房产顾问',
    agentPhone: '138****8888',
    agentWechat: 'agent_888',
    agentStats: {
        experience: 5,
        deals: 200,
        rating: 4.9
    },
    location: {
        longitude: 116.310003, // 中关村经度
        latitude: 39.991957   // 中关村纬度
    }
})

// 周边设施数据
const poiData = reactive({
    公交: [],
    地铁: [],
    医院: [],
    银行: [],
    休闲娱乐: [],
    购物: [],
    餐饮: [],
    运动健身: []
})

// 获取图标名称
const getIconName = (type) => {
    switch (type) {
        case '公交': return 'map/bus'
        case '地铁': return 'map/subway'
        case '医院': return 'map/hospital'
        case '银行': return 'map/bank'
        case '休闲娱乐': return 'map/entertainment'
        case '购物': return 'map/shopping'
        case '餐饮': return 'map/food'
        case '运动健身': return 'map/fitness'
        default: return 'map/default'
    }
}

// 初始化地图
const initMap = async () => {
    console.log('开始初始化地图')
    mapLoading.value = true
    
    try {
        // 1. 在加载 SDK 之前配置安全码
        window._AMapSecurityConfig = {
            securityJsCode: 'dd5f8229f90062eef530f238093f0f0e'  // 替换为你的安全码
        }

        // 2. 加载高德地图SDK，确保包含Driving插件
        const AMap = await AMapLoader.load({
            key: '20043a52000d4a5ba4ac9d73c3f097d0',  // Web端 Key
            version: '2.0',  // 使用新版本
            plugins: ['AMap.PlaceSearch', 'AMap.Driving']  // 添加Driving插件
        })

        console.log('SDK加载成功')

        // 3. 创建地图实例
        map.value = new AMap.Map('amap-container', {
            zoom: 15,
            center: [houseDetail.location.longitude, houseDetail.location.latitude],
            resizeEnable: true
        })

        // 4. 添加房源标记
        new AMap.Marker({
            position: [houseDetail.location.longitude, houseDetail.location.latitude],
            map: map.value,
            title: houseDetail.title
        })

        // 5. 创建搜索实例
        const placeSearch = new AMap.PlaceSearch({
            pageSize: 10,
            pageIndex: 1,
            extensions: 'all'
        })

        // 6. 定义搜索类型
        const searchTypes = {
            '公交': '公交车站',
            '地铁': '地铁站',
            '医院': '医院',
            '银行': '银行',
            '休闲娱乐': '休闲娱乐',
            '购物': '购物',
            '餐饮': '餐饮',
            '运动健身': '健身'
        }

        // 7. 执行周边搜索
        for (const [category, keyword] of Object.entries(searchTypes)) {
            try {
                await new Promise((resolve) => {
                    placeSearch.searchNearBy(
                        keyword,
                        [houseDetail.location.longitude, houseDetail.location.latitude],
                        1000,
                        (status, result) => {
                            console.log(`搜索${category}设施:`, status, result)
                            if (status === 'complete' && result.poiList) {
                                poiData[category] = result.poiList.pois.map(poi => ({
                                    name: poi.name,
                                    distance: poi.distance,
                                    location: poi.location
                                }))
                            }
                            resolve()
                        }
                    )
                })
            } catch (error) {
                console.error(`搜索${category}设施失败:`, error)
                poiData[category] = []
            }
        }

        console.log('周边设施搜索完成:', poiData)
    } catch (error) {
        console.error('地图初始化失败:', error)
        ElMessage.error('地图加载失败，请刷新重试')
    } finally {
        mapLoading.value = false
    }
}

// 点击设施时显示位置和规划路线
const showFacilityLocation = (facility) => {
    // 聚焦到设施位置
    map.value.setCenter([facility.location.lng, facility.location.lat])

    // 添加标记
    new AMap.Marker({
        position: [facility.location.lng, facility.location.lat],
        map: map.value,
        title: facility.name,
        icon: new AMap.Icon({
            image: '/images/map/facility-marker.png', // 自定义图标
            size: new AMap.Size(32, 32),
            imageSize: new AMap.Size(32, 32)
        })
    })

    // 规划路线，从房产位置到设施位置
    const propertyLocation = new AMap.LngLat(houseDetail.location.longitude, houseDetail.location.latitude)

    // 确保设施位置有效
    if (facility.location && facility.location.lng && facility.location.lat) {
        const facilityLocation = new AMap.LngLat(facility.location.lng, facility.location.lat)

        // 清除之前的路线
        if (drivingRoute.value) {
            drivingRoute.value.clear()
        }

        const driving = new AMap.Driving({
            map: map.value
        })

        driving.search(propertyLocation, facilityLocation, (status, result) => {
            if (status === 'complete') {
                console.log('路线规划成功:', result)
                drivingRoute.value = driving // 保存当前路线
            } else {
                console.error('路线规划失败:', result)
            }
        })
    } else {
        console.error('设施位置无效:', facility.location)
    }
}

// 格式化价格
const formatPrice = (price) => {
    return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取房源详情
const fetchHouseDetail = async () => {
    loading.value = true
    try {
        const response = await getHouseDetail(route.params.id)
        console.log('房源详情API响应:', response)
        if (response.code === 200) {
            const data = response.data
            console.log('房源详情原始数据:', data)
            
            // 1. 处理图片信息
            let imagesList = []
            if (data.images && data.images.length > 0) {
                imagesList = data.images
            } else if (data.imageList && data.imageList.length > 0) {
                imagesList = data.imageList
            }
            
            // 2. 基本信息设置
            Object.assign(houseDetail, {
                houseId: data.houseId || data.id,
                title: data.title,
                price: data.price,
                coverImage: data.coverImage || '',
                images: imagesList.length > 0 ? imagesList : (data.coverImage ? [data.coverImage] : []),
                tags: data.tags || [],
                area: data.area,
                bedroom: data.bedroom,
                bathroom: data.bathroom,
                livingRoom: data.livingRoom,
                floor: data.floor,
                totalFloor: data.totalFloor,
                orientation: data.orientation,
                address: data.address,
                features: [
                    {
                        icon: 'house/features/location',
                        title: '地理位置',
                        description: data.locationDesc || '暂无描述'
                    },
                    {
                        icon: 'house/features/decoration',
                        title: '装修情况',
                        description: data.decorationDesc || '暂无描述'
                    },
                    {
                        icon: 'house/features/layout',
                        title: '户型特点',
                        description: data.layoutDesc || '暂无描述'
                    },
                    {
                        icon: 'house/features/community',
                        title: '小区环境',
                        description: data.communityDesc || '暂无描述'
                    }
                ],
                description: data.description || '暂无描述',
                facilities: data.facilities || [],
                location: {
                    longitude: data.lng || 116.310003,
                    latitude: data.lat || 39.991957
                }
            })
            
            // 收藏状态
            isCollected.value = data.isCollected || false
            
            // 3. 经纪人信息处理
            await processAgentInfo(data)
        } else {
            ElMessage.error(response.msg || '获取房源详情失败')
        }
    } catch (error) {
        console.error('获取房源详情失败:', error)
        ElMessage.error('获取房源详情失败，请稍后重试')
    } finally {
        loading.value = false
    }
    await initMap() // 在获取到房源信息后初始化地图
}

// 经纪人信息处理 - 独立函数使逻辑更清晰
const processAgentInfo = async (data) => {
    try {
        console.log('开始处理经纪人信息')
        
        // 1. 从各种可能的字段中提取经纪人ID
        const agentId = getAgentIdFromData(data)
        
        if (agentId) {
            console.log('找到经纪人ID:', agentId)
            // 2. 使用ID设置初始经纪人信息
            setInitialAgentInfo(data, agentId)
            
            // 3. 通过API获取完整的经纪人信息
            const success = await fetchAndEnrichAgentInfo(agentId)
            
            if (!success) {
                console.warn('使用经纪人ID获取信息失败，房源ID:', route.params.id, '经纪人ID:', agentId)
            }
        } else {
            console.warn('未找到经纪人ID，尝试获取默认经纪人')
            // 4. 尝试获取默认经纪人
            const gotDefaultAgent = await getDefaultAgent()
            if (!gotDefaultAgent) {
                console.warn('没有可用的经纪人信息')
            }
        }
        
        // 最后检查是否成功设置了经纪人
        if (!houseDetail.agentId || !houseDetail.agentName || houseDetail.agentName === '暂无经纪人') {
            console.warn('经过所有尝试后仍未获取到有效经纪人信息')
        } else {
            console.log('最终应用的经纪人信息:', {
                id: houseDetail.agentId,
                name: houseDetail.agentName,
                avatar: houseDetail.agentAvatar
            })
        }
    } catch (error) {
        console.error('处理经纪人信息失败:', error)
    }
}

// 从数据中提取经纪人ID
const getAgentIdFromData = (data) => {
    console.log('开始从原始数据中提取经纪人ID')
    // 原始数据中可能包含的经纪人ID字段
    const directId = data.agentId
    const agentObjectId = data.agent?.id || data.agent?.agentId
    const agentUnderscore = data.agent_id
    const agentInfoId = data.agentInfo?.id || data.agentInfo?.agentId
    
    // 打印所有可能的字段
    console.log('原始数据经纪人相关字段:', {
        'data.agentId': directId,
        'data.agent?.id/agentId': agentObjectId,
        'data.agent_id': agentUnderscore,
        'data.agentInfo?.id/agentId': agentInfoId,
        'data.agent': data.agent
    })
    
    // 尝试从URL中提取可能存在的经纪人ID
    const urlParams = new URLSearchParams(window.location.search)
    const urlAgentId = urlParams.get('agentId')
    if (urlAgentId) {
        console.log('从URL参数中获取到经纪人ID:', urlAgentId)
        return urlAgentId
    }
    
    // 按优先级返回经纪人ID
    if (directId) {
        console.log('从data.agentId获取到经纪人ID:', directId)
        return directId
    }
    
    if (agentObjectId) {
        console.log('从data.agent对象获取到经纪人ID:', agentObjectId)
        return agentObjectId
    }
    
    if (agentUnderscore) {
        console.log('从data.agent_id获取到经纪人ID:', agentUnderscore)
        return agentUnderscore
    }
    
    if (agentInfoId) {
        console.log('从data.agentInfo获取到经纪人ID:', agentInfoId)
        return agentInfoId
    }
    
    console.warn('未能从任何字段获取到经纪人ID')
    return null
}

// 设置初始经纪人信息
const setInitialAgentInfo = (data, agentId) => {
    console.log('设置初始经纪人信息')
    Object.assign(houseDetail, {
        agentId: agentId,
        agentName: data.agentName || '暂无经纪人',
        agentAvatar: data.agentAvatar || '/profile/avatars/default-avatar.jpg',
        agentTitle: data.agentTitle || '房产顾问',
        agentPhone: data.agentPhone || '暂无联系方式',
        agentWechat: data.agentWechat || '暂无微信',
        agentExperience: data.agentExperience || 0,
        agentDeals: data.agentDeals || 0,
        agentRating: data.agentRating || 0,
        agentStats: {
            experience: data.agentExperience || 0,
            deals: data.agentDeals || 0,
            rating: data.agentRating || 0
        }
    })
}

// 获取并丰富经纪人信息
const fetchAndEnrichAgentInfo = async (agentId) => {
    try {
        console.log('开始获取完整经纪人信息, ID:', agentId)
        
        // 直接调用API获取经纪人信息
        const res = await getAgentInfo(agentId)
        console.log('经纪人API响应:', res)
        
        if (res.code === 200 && res.data) {
            const agentInfo = res.data
            console.log('获取到的经纪人详细信息:', agentInfo)
            
            // 1. 尝试从经纪人信息中直接获取用户ID
            let userId = agentInfo.userId || agentInfo.user_id
            
            // 2. 如果没有用户ID，尝试通过专门的API获取
            if (!userId) {
                try {
                    const userIdRes = await getAgentUserId(agentId)
                    console.log('获取经纪人用户ID响应:', userIdRes)
                    if (userIdRes.code === 200 && userIdRes.data) {
                        userId = userIdRes.data.userId || userIdRes.data.user_id || userIdRes.data
                        console.log('通过API获取到的用户ID:', userId)
                    }
                } catch (userIdError) {
                    console.error('获取经纪人用户ID失败:', userIdError)
                }
            }
            
            // 3. 如果还是没有，假设用户ID就是经纪人ID (后端可能会映射)
            if (!userId) {
                userId = agentId
                console.warn('未找到经纪人用户ID，假设用户ID等于经纪人ID:', userId)
            }
            
            console.log('最终确定的聊天用户ID:', userId)
            
            // 直接从API响应中提取经纪人信息并更新
            Object.assign(houseDetail, {
                agentId: agentId,                 // 经纪人ID（经纪人表的ID）
                chatUserId: userId,               // 聊天使用的用户ID
                agentName: agentInfo.name || agentInfo.realName || houseDetail.agentName,
                agentAvatar: agentInfo.avatar || houseDetail.agentAvatar,
                agentTitle: agentInfo.title || houseDetail.agentTitle,
                agentPhone: agentInfo.phone || houseDetail.agentPhone,
                agentWechat: agentInfo.wechat || houseDetail.agentWechat,
                agentExperience: agentInfo.yearsOfExperience || agentInfo.experience || houseDetail.agentExperience,
                agentDeals: agentInfo.totalSales || agentInfo.deals || houseDetail.agentDeals,
                agentRating: agentInfo.rating || houseDetail.agentRating
            })
            
            // 更新统计信息
            houseDetail.agentStats = {
                experience: agentInfo.yearsOfExperience || agentInfo.experience || houseDetail.agentExperience || 0,
                deals: agentInfo.totalSales || agentInfo.deals || houseDetail.agentDeals || 0,
                rating: agentInfo.rating || houseDetail.agentRating || 0
            }
            
            console.log('更新后的经纪人信息:', {
                agentId: houseDetail.agentId,
                chatUserId: houseDetail.chatUserId,
                agentName: houseDetail.agentName,
                agentAvatar: houseDetail.agentAvatar
            })
            
            return true
        } else {
            console.warn('经纪人信息获取失败或数据为空')
            return false
        }
    } catch (error) {
        console.error('获取完整经纪人信息失败:', error)
        return false
    }
}

// 检查收藏状态
const checkCollectStatus = async () => {
  try {
    // 检查ID是否有效
    const houseId = route.params.id
    if (!houseId) {
      console.warn('检查收藏状态：无效的房源ID')
      return
    }
    
    const res = await checkFavorite(houseId)
    if (res.code === 200) {
      // 根据后端返回的结构适配，后端可能直接返回collected字段或嵌套在data中
      isCollected.value = res.data?.collected || res.collected || false
      
      // 获取收藏时间（如果有）
      const collectTime = res.data?.collectTime || res.collectTime
      if (collectTime && isCollected.value) {
        console.log('收藏时间:', dayjs(collectTime).format('YYYY-MM-DD HH:mm'))
      }
      
      // 获取收藏总数（如果有）
      const total = res.data?.total || res.total
      if (total !== undefined) {
        console.log('当前收藏总数:', total)
      }
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 处理收藏/取消收藏
const toggleCollect = async () => {
  try {
    // 检查ID是否有效
    const houseId = route.params.id
    if (!houseId) {
      ElMessage.error('无效的房源ID')
      return
    }
    
    if (isCollected.value) {
      // 取消收藏
      const res = await removeFavorite(houseId)
      if (res.code === 200) {
        ElMessage.success('取消收藏成功')
        isCollected.value = false
      } else {
        ElMessage.error(res.msg || '取消收藏失败')
      }
    } else {
      // 添加收藏
      const res = await addFavorite(houseId)
      if (res.code === 200) {
        ElMessage.success('收藏成功')
        isCollected.value = true
      } else {
        ElMessage.error(res.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('操作收藏失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 联系经纪人
const contactAgent = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    loginStore.showLogin()
    return
  }
  
  // 确保有聊天需要的信息
  if (!houseDetail.agentId) {
    ElMessage.warning('无法获取经纪人联系方式，请稍后再试')
    return
  }
  
  // 使用经纪人名称和聊天用户ID
  const agentName = houseDetail.agentName || '经纪人'
  // 优先使用chatUserId，如果没有则使用agentId
  const chatUserId = houseDetail.chatUserId || houseDetail.agentId
  
  console.log('联系经纪人', {
    经纪人ID: houseDetail.agentId,
    聊天用户ID: chatUserId,
    经纪人名称: agentName,
    房源ID: houseDetail.houseId
  })
  
  try {
    // 发起聊天请求，使用agentId获取聊天用户ID，并传递预设消息
    startChat({
      agentId: houseDetail.agentId,
      houseId: houseDetail.houseId,
      message: `您好，我对您的房源(${houseDetail.title})感兴趣，想了解更多信息。`
    }).then(res => {
      console.log('创建聊天响应:', res)
      if (res.code === 200) {
        // 聊天创建成功后跳转到聊天页面，附带更多参数以确保匹配成功
        // 重要：使用chatUserId作为targetUserId参数传递，而不是agentId
        router.push({
          path: '/chat',
          query: {
            agentId: houseDetail.agentId, // 保留原始经纪人ID以供参考
            targetUserId: chatUserId, // 使用chatUserId作为聊天目标ID
            agentName: agentName,
            agentAvatar: houseDetail.agentAvatar,
            houseId: houseDetail.houseId,
            chatSuccess: 'true',
            t: new Date().getTime() // 添加时间戳避免路由缓存
          }
        })
      } else {
        console.error('创建聊天失败:', res)
        // 错误处理：使用备用方法
        useBackupChatMethod()
      }
    }).catch(error => {
      console.error('创建聊天失败:', error)
      // 错误处理：使用备用方法
      useBackupChatMethod()
    })
  } catch (error) {
    console.error('联系经纪人操作失败:', error)
    // 错误处理：使用备用方法
    useBackupChatMethod()
  }
}

// 备用聊天方法
const useBackupChatMethod = () => {
  const agentName = houseDetail.agentName || '经纪人'
  // 优先使用chatUserId，如果没有则使用agentId
  const chatUserId = houseDetail.chatUserId || houseDetail.agentId
  
  ElMessage.warning('正在使用备用方式连接聊天...')
  
  // 直接跳转到聊天页面
  router.push({
    path: '/chat',
    query: {
      agentId: houseDetail.agentId, // 保留原始经纪人ID以供参考
      targetUserId: chatUserId, // 使用chatUserId作为聊天目标ID
      agentName: agentName, 
      agentAvatar: houseDetail.agentAvatar,
      houseId: houseDetail.houseId,
      directStart: 'true',  // 告诉聊天页面直接开始聊天
      t: new Date().getTime() // 添加时间戳避免路由缓存
    }
  })
}

// 联系客服
const contactCustomerService = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    loginStore.showLogin()
    return
  }
  
  // 这里可以弹出客服联系信息或跳转到客服页面
  ElMessage.success('即将为您连接客服，请稍候...')
  
  // 这里可以根据实际需求跳转到客服页面或打开客服聊天窗口
  // 例如跳转到客服页面
  router.push({
    path: '/customer-service',
    query: {
      source: 'house-detail',
      houseId: houseDetail.houseId
    }
  })
}

// 获取默认经纪人信息
const getDefaultAgent = async () => {
  try {
    // 如果已经有经纪人ID，则不获取默认经纪人
    if (houseDetail.agentId) {
      console.log('已有经纪人ID，不获取默认经纪人:', houseDetail.agentId)
      return true
    }
    
    console.log('尝试获取默认经纪人...');
    // 获取经纪人列表的第一个
    const res = await getAgentList({ pageNum: 1, pageSize: 1 });
    
    if (res.code === 200 && res.data && res.data.records && res.data.records.length > 0) {
      const defaultAgent = res.data.records[0];
      console.log('找到默认经纪人:', defaultAgent);
      
      // 提取用户ID
      const userId = defaultAgent.userId || defaultAgent.user_id || defaultAgent.id;
      console.log('默认经纪人的用户ID:', userId);
      
      // 更新房源的经纪人信息
      houseDetail.agentId = defaultAgent.id || defaultAgent.agentId;
      houseDetail.chatUserId = userId; // 设置聊天用户ID
      houseDetail.agentName = defaultAgent.name || defaultAgent.realName || '默认经纪人';
      houseDetail.agentAvatar = defaultAgent.avatar || '/images/agent/avatar-default.png';
      houseDetail.agentTitle = defaultAgent.title || '房产顾问';
      houseDetail.agentPhone = defaultAgent.phone || '暂无联系方式';
      houseDetail.agentWechat = defaultAgent.wechat || '';
      
      // 更新经纪人统计信息
      houseDetail.agentStats = {
        experience: defaultAgent.yearsOfExperience || defaultAgent.experience || 0,
        deals: defaultAgent.totalSales || defaultAgent.deals || 0,
        rating: defaultAgent.rating || 5.0,
        views: defaultAgent.totalViews || defaultAgent.views || 0
      };
      
      return true;
    } else {
      console.warn('未找到默认经纪人');
      return false;
    }
  } catch (error) {
    console.error('获取默认经纪人失败:', error);
    return false;
  }
};

onMounted(async () => {
    console.log('组件挂载')
    try {
        await nextTick()
        console.log('DOM更新完成，开始加载房源ID:', route.params.id)
        
        // 添加路由参数校验
        if (!route.params.id) {
            console.error('无效的房源ID')
            ElMessage.error('无效的房源ID')
            router.push('/house')
            return
        }
        
        await fetchHouseDetail() // 修改为先获取房源详情
        
        // 检查是否成功获取了经纪人信息
        if (!houseDetail.agentId) {
            console.warn('获取房源详情后仍然没有经纪人ID，尝试应用默认经纪人')
            await getDefaultAgent()
        }
        
        await checkCollectStatus()
    } catch (error) {
        console.error('组件加载失败:', error)
        ElMessage.error('加载失败，请稍后重试')
    }
})

// 确保组件卸载时清理资源
onUnmounted(() => {
    if (map.value) {
        map.value.destroy()
    }
})

// 地图控件功能
const zoomIn = () => {
    if (map.value) {
        map.value.setZoom(map.value.getZoom() + 1); // 放大地图
    }
}

const zoomOut = () => {
    if (map.value) {
        map.value.setZoom(map.value.getZoom() - 1); // 缩小地图
    }
}

const resetView = () => {
    if (map.value) {
        map.value.setCenter([houseDetail.location.longitude, houseDetail.location.latitude]); // 重置视图
        map.value.setZoom(15); // 重置缩放级别
    }
}

// 处理图片列表
const houseImages = computed(() => {
    let images = [];
    
    // 如果响应中有图片数组
    if (houseDetail.images && houseDetail.images.length > 0) {
        // 处理图片URL
        images = houseDetail.images.map(img => {
            if (typeof img === 'string') {
                return getFullImageUrl(img);
            } else if (img && img.imageUrl) {
                return getFullImageUrl(img.imageUrl);
            }
            return '';
        }).filter(url => url); // 过滤掉空URL
    }
    
    // 如果有封面图但不在images中，添加到第一位
    if (houseDetail.coverImage && !images.includes(getFullImageUrl(houseDetail.coverImage))) {
        images.unshift(getFullImageUrl(houseDetail.coverImage));
    }
    
    // 如果没有图片，显示默认图片
    if (images.length === 0) {
        images = ['/images/house/default-house.jpg'];
    }
    
    return images;
})

// 处理经纪人头像
const agentAvatar = computed(() => {
    // 直接从houseDetail中获取头像
    const avatar = houseDetail.agentAvatar;
    
    // 如果头像为空，使用默认头像
    if (!avatar || avatar.includes('default') || avatar === '/profile/avatars/default-avatar.jpg') {
        return '/images/agent/avatar-default.png';
    }
    
    // 处理不同格式的URL
    return getFullImageUrl(avatar);
})
</script>

<style lang="scss" scoped>
.house-detail {
    width: 100%;
    display: flex;
    flex-direction: column;
    
    .container {
        width: 100%;
        padding: 0 60px;
        box-sizing: border-box;
        margin: 60px auto;
        
        @media (max-width: 768px) {
            padding: 0 20px;
            margin: 30px auto;
        }
        
        .content-wrapper {
            max-width: 1320px;
            margin: 0 auto;
            
            > * {
                margin-bottom: 40px;
                
                &:last-child {
                    margin-bottom: 0;
                }
            }
            
            .basic-info {
                display: grid;
                grid-template-columns: 720px 1fr;
                gap: 40px;
                
                .left {
                    :deep(.el-carousel) {
                        border-radius: 8px;
                        overflow: hidden;
                        
                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                        }
                    }
                }
                
                .right {
                    .title {
                        font-size: 28px;
                        font-weight: 600;
                        color: #2F3B59;
                        margin-bottom: 24px;
                    }
                    
                    .price {
                        margin-bottom: 24px;
                        
                        .amount {
                            font-size: 32px;
                            font-weight: 600;
                            color: #4A60A1;
                        }
                    }
                    
                    .tags {
                        margin-bottom: 24px;
                        
                        .el-tag {
                            margin-right: 8px;
                            margin-bottom: 8px;
                        }
                    }
                    
                    .info-items {
                        display: grid;
                        grid-template-columns: repeat(2, 1fr);
                        gap: 16px;
                        margin-bottom: 24px;
                        
                        .item {
                            display: flex;
                            align-items: center;
                            gap: 8px;
                            color: #2F3B59;
                            
                            .svg-icon {
                                width: 24px;
                                height: 24px;
                                color: #4A60A1;
                            }
                        }
                    }
                    
                    .address {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        color: #2F3B59;
                        margin-bottom: 32px;
                        
                        .svg-icon {
                            width: 24px;
                            height: 24px;
                            color: #4A60A1;
                        }
                    }
                    
                    .buttons {
                        display: flex;
                        gap: 16px;
                        
                        .el-button {
                            flex: 1;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                            
                            .svg-icon {
                                width: 20px;
                                height: 20px;
                            }
                        }
                    }
                }
            }
            
            .card {
                background: #fff;
                border-radius: 8px;
                padding: 32px;
                margin-bottom: 24px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
                
                .section-title {
                    font-size: 24px;
                    font-weight: 600;
                    color: #2F3B59;
                    margin-bottom: 24px;
                }
            }
            
            .features {
                .feature-list {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 24px;
                    
                    .feature-item {
                        display: flex;
                        gap: 16px;
                        
                        .svg-icon {
                            width: 48px;
                            height: 48px;
                            color: #4A60A1;
                        }
                        
                        .feature-content {
                            h3 {
                                font-size: 18px;
                                font-weight: 600;
                                color: #2F3B59;
                                margin-bottom: 8px;
                            }
                            
                            p {
                                color: #6D737A;
                                line-height: 1.5;
                            }
                        }
                    }
                }
            }
            
            .description {
                .description-content {
                    color: #2F3B59;
                    line-height: 1.8;
                    
                    :deep(p) {
                        margin-bottom: 16px;
                        
                        &:last-child {
                            margin-bottom: 0;
                        }
                    }
                }
            }
            
            .facilities {
                .facility-list {
                    display: grid;
                    grid-template-columns: repeat(6, 1fr);
                    gap: 24px;
                    
                    .facility-item {
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        gap: 8px;
                        
                        .svg-icon {
                            width: 32px;
                            height: 32px;
                            color: #4A60A1;
                            
                            &.disabled {
                                color: #C0C4CC;
                            }
                        }
                        
                        span {
                            color: #2F3B59;
                            
                            &.disabled {
                                color: #C0C4CC;
                            }
                        }
                    }
                }
            }
            
            .agent-info {
                .agent-content {
                    display: flex;
                    gap: 32px;
                    
                    .agent-avatar {
                        width: 120px;
                        height: 120px;
                        border-radius: 60px;
                        overflow: hidden;
                        
                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                        }
                    }
                    
                    .agent-details {
                        flex: 1;
                        
                        h3 {
                            font-size: 24px;
                            font-weight: 600;
                            color: #2F3B59;
                            margin-bottom: 8px;
                        }
                        
                        .agent-title {
                            color: #6D737A;
                            margin-bottom: 24px;
                        }
                        
                        .agent-stats {
                            display: flex;
                            gap: 48px;
                            margin-bottom: 24px;
                            
                            .stat-item {
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                
                                .value {
                                    font-size: 24px;
                                    font-weight: 600;
                                    color: #4A60A1;
                                }
                                
                                .label {
                                    color: #6D737A;
                                    margin-top: 4px;
                                }
                            }
                        }
                    }
                }
            }
            
            .map-container {
                position: relative;
                
                .map-wrapper {
                    position: relative;
                    display: flex;
                    gap: 20px;

                    #amap-container {
                        width: 100%;
                        height: 500px;
                        border-radius: 8px;
                        overflow: hidden;
                        position: relative;
                    }

                    .poi-list {
                        position: absolute;
                        top: 10px;
                        right: 10px;
                        width: 300px;
                        max-height: 480px;
                        overflow-y: auto;
                        background: white;
                        border-radius: 8px;
                        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                        z-index: 10;
                    }

                    /* 地图控件样式 */
                    .map-controls {
                        position: absolute;
                        bottom: 20px;
                        left: 20px;
                        display: flex;
                        flex-direction: column;
                        gap: 10px;

                        button {
                            width: 40px;
                            height: 40px;
                            background-color: #fff;
                            border: 1px solid #ccc;
                            border-radius: 5px;
                            cursor: pointer;
                            font-size: 18px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                    }
                }

                .map-loading {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(255, 255, 255, 0.8);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 999;
                }

                .no-data {
                    text-align: center;
                    padding: 20px;
                    color: #999;
                }
            }
        }
    }
}

.contact-dialog {
    .agent-info {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 24px;
        
        img {
            width: 64px;
            height: 64px;
            border-radius: 32px;
            object-fit: cover;
        }
        
        .info {
            h3 {
                font-size: 18px;
                font-weight: 600;
                color: #2F3B59;
                margin-bottom: 4px;
            }
            
            p {
                color: #6D737A;
            }
        }
    }
    
    .contact-methods {
        .method {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px;
            background: #F5F6FA;
            border-radius: 4px;
            margin-bottom: 12px;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .svg-icon {
                width: 24px;
                height: 24px;
                color: #4A60A1;
            }
            
            span {
                font-size: 16px;
                color: #2F3B59;
            }
        }
    }
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .svg-icon {
        width: 80px;
        height: 80px;
        color: #C0C4CC;
        margin-bottom: 16px;
    }
    
    p {
        color: #909399;
        font-size: 16px;
        margin-bottom: 10px;
    }
    
    .empty-desc {
        color: #C0C4CC;
        font-size: 14px;
        margin-bottom: 24px;
        text-align: center;
    }
    
    .el-button {
        min-width: 140px;
    }
}
</style> 